package com.guapi.service.impl;

import com.guapi.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

public class CacheServiceImpl<E> implements CacheService<E> {
    private String PREFIX="prefix";
    private String SPLIT=":";

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<E> getCache(String key) {
        return redisTemplate.opsForList().range(PREFIX+SPLIT+key, 0, -1);
    }

    @Override
    public void setCache(String key, List object) {
        for (Object o : object) {
            redisTemplate.opsForList().leftPush(PREFIX+SPLIT+key,o);
        }
    }

    /**
     * 清除缓存
     * @param key
     */
    @Override
    public void deleteCache(String key) {
        List<E> userList = redisTemplate.opsForList().range(PREFIX+SPLIT+key, 0, -1);
        for (int i = 0; i < userList.size(); i++){
            redisTemplate.opsForList().leftPop(PREFIX+SPLIT+key);
        }
    }
}
